package com.example.oom;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtNewMethod;

import java.util.ArrayList;
import java.util.List;

public class MetaspaceOOMWithJavassist {
    public static void main(String[] args) throws Exception {
        // 用于防止类被 GC 掉，否则元空间不会一直增长
        List<Class<?>> generatedClasses = new ArrayList<>();
        ClassPool pool = ClassPool.getDefault();

        int count = 0;
        try {
            while (true) {
                // 创建一个新的类
                CtClass ctClass = pool.makeClass("com.example.GeneratedClass" + count);

                // 给这个类添加一个新方法，避免被优化合并
                String methodBody = "public void method" + count + "() { System.out.println(" + count + "); }";
                ctClass.addMethod(CtNewMethod.make(methodBody, ctClass));

                // 加载该类（写入 Metaspace）
                Class<?> clazz = ctClass.toClass();

                // 保存引用，防止被回收
                generatedClasses.add(clazz);

                count++;

                if (count % 100 == 0) {
                    System.out.println("Generated classes: " + count);
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            System.out.println("Total generated classes before OOM: " + count);
        }
    }
}
